<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License 
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: ModelTable.php 262 2011-07-23 15:51:14Z beimuaihui $
 */


Zend_Loader::loadClass("Baogg_Db_Table");

//class Permission extends Baogg_Db_Table {
class ModelTable  extends Baogg_Db_Table {
	/**
	 * The default table name 
	 */
	protected $_name;
	protected $_db ;
	protected $_primary; 
	protected $cols;
	protected $my_model_id;
	
	function __construct($model_id) {		
		$this->my_model_id=$model_id;
		
		$this->cols=array();
		
		$model=new Model();
		$rs_model=$model->getList(array("model_id"=>$model_id));
		if(!$rs_model){
			throw new Exception("Baogg Errror:Unknow model");
		}		
		$this->_name =   $rs_model[0]['ext_table'];
		
		
		$model_field=new ModelField();
		$rs_model_field=$model_field->getList(array("model_id"=>$model_id,"state"=>1), array("sort"=>"ordering","dir"=>"asc"));
		foreach((array)$rs_model_field as $v){
			if($v['field_key']=='PRI'){
				$this->primary= $this->_primary=$v['field_name'];
			}
			if(!$v['is_main']){
				$this->cols[]=$v['field_name'];
			}
		}		
		
		
		parent::__construct();
	//	just for temp,not exist model_field list
		if(!$rs_model){
			$rs_field=$this->_db->query("desc ".$this->db_prefix.$rs_model[0]['table_name']);
			foreach($rs_field as $v){
				if($v['Key']=='PRI'){
					$this->primary= $this->_primary=$v['Field'];
				}
				$this->cols[]=$v['Field'];
			}
		}
	}
	
	
	function getSame($arr) {	
		$ret=array();
		
		$where[$this->primary]=$arr[$this->primary];
	    parent::getSame($where);
		return $ret; 	
	
	}
	
	
	function filterForm($form=array()){
		
		
		foreach((array)$form as $k=>$v){
			//&& $k!='query'
			if(!in_array($k,$this->cols) ){
				unset($form[$k]);
			}
		}
		return $form;
		
	}
	
	function getShowList($where=array(),$order=array(),$limit=array(),$cols="*"){
		
		//get list
		$rs=$this->getList($where,$order,$limit,$cols);
		
		//get column,show name
		$ModelField=new ModelField();
		$rs_field=$ModelField->getList(array("model_id"=>$this->my_model_id));
		foreach((array)$rs_field as $v){
			$arr_field[$v['field_name']]=$v['show_name'];
		}
		
		//convert col to show col
		foreach((array)$rs as $k=>$v){
			foreach($v as $col=>$row){
				$new_col=@$arr_field[$col];
				$rs[$k][$new_col]=$row;
			}
		}
		
		return $rs;
	}
	
	/**
	 * @legacy
	 * @param model_field.field_option value $options
	 * @param row data for grid,url param for form $params
	 * @param int,1 stands for grid,0 stands for form view, view $pos
	 */
	static function handleFieldOptionsLegacy($options,$params=array(),$pos="form"){
		global $LANG;
		
		$db=Zend_Registry::get("db");
		$item=array();
		
		$arr_option=explode(";",$options);//separated by form combo store,grid  store
		$options=isset($arr_option[$pos])?$arr_option[$pos]:$arr_option[0];
		
		if(!strpos($options,'=')){
			return $item;
		}
		
		$source=array();
		$arr_data=explode("=",trim($options),2);
		//$arr_data[1]=compile($arr_data[1]);		
		if($arr_data[0]=="sql"){
			preg_match_all("/:[\d\w\_]+/", $arr_data[1], $matches);
			if($matches){
				foreach(@$matches[0] as $v){
					$v_name=trim($v,":");
					$arr_data[1]=str_replace($v,@$params[$v_name],$arr_data[1]);
				}
			}
			//echo '<pre>';print_r($arr_data);print_r($params);var_dump($arr_data[1]);exit;
			try{
				$rs=$db->query($arr_data[1])->fetchAll();
				//tree combo
				if(count((array)$rs[0])==3){
					$objTree=new Baogg_Db_Tree();
					$tr=$objTree->rs2ComboTree($rs);
					$source=$objTree->tr2ComboStore($tr);
				}else{
					$rs=$db->query($arr_data[1])->fetchAll();
					$columns=array_keys($rs[0]);
					foreach((array)$rs as $v){
						$source[]=array($v[$columns[0]],$v[$columns[1]]);
					}
				}
			}catch(Exception $e){
				
			}
			//echo '<pre>';print_r($source);exit;
			$item['store']=$source;
			$item['source']=$source;
		}else if($arr_data[0]=="lang"){
			$arr_lang=$LANG[$arr_data[1]];
			foreach((array)$arr_lang as $k=>$v){
				$source[]=array($k,$v);
			}
			$item['store']=$source;
			$item['source']=$source;
		}else if($arr_data[0]=="url"){

			$url=trim($arr_data[1],"/");
			$arr_url=explode("/",$url);
			if(!is_array($arr_url) || count($arr_url)<5){
				throw new Exception(BAOGG_LANGUAGE::get("msg_config_combo_url_error"));
			}
			$data_url=BAOGG_BASE_URL.$arr_url[0].'/'.$arr_url[1].'/'.$arr_url[2].'/';
			foreach($arr_url as $v){
				if(strpos($v,":")===0 ){
					$v=trim($v,",");
					if( isset($params[$v])){
						$data_url.=$v.'/'.$params[$v].'/';
					}
				}
			}
			$item['displayField']=trim($arr_url[4],":");
			$item['valueField']=trim($arr_url[3],":");
			
			$item['fields']=array($item['valueField'],$item['displayField']);			
			$item['pageSize']=20;
			$item['mode']='remote';
			$item['loadingText']=BAOGG_LANGUAGE::get("searcing");
			$item['minChars']=1;
			//$item['store']=new Zend_Json_Expr('new Ext.data.JsonStore({proxy: new Ext.data.HttpProxy({url: "'.$data_url.'"}),reader: new Ext.data.JsonReader({root: "data",totalProperty: "count",id: "'.$col_id.'"}, ["'.$col_id.'","'.$item['displayField'].'"])})');
			$item['store']=new Zend_Json_Expr('new Ext.data.JsonStore({root: "data",totalProperty: "count",idProperty: "id",remoteSort: true,fields: ["'.$item['valueField'].'","'.$item['displayField'].'"],autoLoad:true,proxy: new Ext.data.HttpProxy({url: "'.$data_url.'"})})');
		}else{
			$arr_data=explode("|",trim($options));
			foreach((array)$arr_data as $v){
				$source[]=explode("=>",$v);
			}
			$item['source']=$source;
			$item['store']=$source;
		}
		
		return $item;
		
	}
	

	/**
	 * 
	 * @param model_field.field_option value,or php json array,not use $pos.url must contain field1 for id,field2 for text $options
	 * @param row data for grid,url param for form $params
	 * @param int,1 stands for grid,0 stands for form view, view $pos
	 */
	static function handleFieldOptions($options,$params=array(),$pos="form"){
		global $LANG;
		
		$db=Zend_Registry::get("db");
		$item=array("source"=>array(),"store"=>array());
		
		if(is_string($options)){
			try{
				$options=Zend_Json::decode($options);
			}catch(Exception $e){				
				echo __FILE__.__LINE__.'<pre>';var_dump($options);exit;
			}
			$options=$options[$pos];
		}
		if(!is_array($options)){
			return array();
		}
				
		
		//$arr_data[1]=compile($arr_data[1]);		
		if(isset($options["sql"])){
			preg_match_all("/:[\d\w\_]+/", $options["sql"], $matches);
			if($matches){
				foreach(@$matches[0] as $v){
					$v_name=trim($v,":");
					$options["sql"]=str_replace($v,@$params[$v_name],$options["sql"]);
				}
			}
			//echo '<pre>';print_r($arr_data);print_r($params);var_dump($arr_data[1]);exit;
			try{
				$rs=$db->query($options["sql"])->fetchAll();
				
				//tree combo
				if(count((array)$rs[0])==3){
					$objTree=new Baogg_Db_Tree();
					$tr=$objTree->rs2ComboTree($rs);
					$source=$objTree->tr2ComboStore($tr);
				}else{
					$rs=$db->query($options["sql"])->fetchAll();
					$columns=array_keys($rs[0]);
					foreach((array)$rs as $v){
						$source[]=array($v[$columns[0]],$v[$columns[1]]);
					}
				}
			}catch(Exception $e){
				echo __FILE__.__LINE__;
				return array();
			}
			//echo '<pre>';print_r($source);exit;
			$item['store']=$source;
			$item['source']=$source;
		}else if(isset($options["lang"])){
			$arr_lang=@$LANG[$options["lang"]];
			foreach((array)$arr_lang as $k=>$v){
				$source[]=array($k,$v);
			}
			$item['store']=$source;
			$item['source']=$source;
		}else if(isset($options["url"])){

			$arr_url=Baogg_Controller_Url::reverse(trim($options["url"],"/"));// explode("/",$url);// Baogg_Controller_Url::
			if(!is_array($arr_url) || count($arr_url)<3){
				throw new Exception(BAOGG_LANGUAGE::get("msg_config_combo_url_error"));
			}			
			foreach($arr_url as $k=>$v){
				if(strpos($v,":")===0 ){
					$v=trim($v,":");
					if( isset($params[$v])){
						$arr_url[$k]=$params[$v];
					}else{
						unset($arr_url[$k]);
					}
				}
			}
			$item['displayField']=trim($arr_url['field2'],":");
			$item['valueField']=trim($arr_url['field1'],":");
			unset($arr_url['field1']);unset($arr_url['field2']);
			$data_url=Baogg_Controller_Url::generate($arr_url);
			
			$item['fields']=array($item['valueField'],$item['displayField']);			
			$item['pageSize']=20;
			$item['mode']='remote';
			$item['loadingText']=BAOGG_LANGUAGE::get("searcing");
			$item['minChars']=1;
			//$item['store']=new Zend_Json_Expr('new Ext.data.JsonStore({proxy: new Ext.data.HttpProxy({url: "'.$data_url.'"}),reader: new Ext.data.JsonReader({root: "data",totalProperty: "count",id: "'.$col_id.'"}, ["'.$col_id.'","'.$item['displayField'].'"])})');
			$item['store']=new Zend_Json_Expr('new Ext.data.JsonStore({root: "data",totalProperty: "count",idProperty: "id",remoteSort: true,fields: ["'.$item['valueField'].'","'.$item['displayField'].'"],autoLoad:true,proxy: new Ext.data.HttpProxy({url: "'.$data_url.'"})})');
		}else if(isset($options["field_view"]) && $options["field_view"]=="fileuploadfield" && $pos=="grid"){
			$Attachment=new Attachment();
	   		$rs_attachment=$Attachment->getOne($params[$Attachment->myPrimary]);
	   		$row_attachment=$rs_attachment[0];
	   		$item['source']=array(array($row_attachment[$Attachment->myPrimary],'<a href="'.BAOGG_UPLOAD_URL.'upload/'.$row_attachment['module'].'/'.$row_attachment['controller'].'/'.$row_attachment['real_name'].'.'.$row_attachment['suffix'].'">'. $row_attachment['file_name'].'.'.$row_attachment['suffix'].'</a>'));
			
		}else{			
			$item['source']=$options;
			$item['store']=$options;
		}
		//convert array($k=>$v) format when grid		
		if($pos=="grid"){
			$item_grid=array();
			foreach((array)@$item['source'] as $v){
				$item_grid[@$v[0]]=@$v[1];
			}
			$item=$item_grid;			
		}
		return $item;
		
	}

	
}